public with sharing class SalesPerformanceDataImportController {

	public String dataJson {get;private set;}
	public String msg {get;private set;}

	public String searchJson {get; set;}
    public String deleType {get;set;}
    
    public String deleCompany {get;set;}
    public Boolean isIncrease  {get;set;}

    public  Boolean isAssist {get; private set ; }

	private static Map<String,String> fbeanMap = new Map<String,String>();
    static{

        
        Set<String>  fields = new Set<String>();

        Map<String,String>fM = new Map<String,String>();
		Schema.DescribeSobjectResult m = SalesPerformanceDataSheet__c.sObjectType.getDescribe();
	    Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();
	    for (String field : fieldMap.keySet()) {
             Schema.SObjectField sf  = fieldMap.get(field);
            
             fbeanMap.put(sf.getDescribe().getLocalName(),sf.getDescribe().getType()+''); 
             
	    }


    }
    public SalesPerformanceDataImportController() {
        
        User u = [select Profile.Name ,Name from User where Id=:UserInfo.getUserId()];

         isAssist = u.Profile.Name == '系统管理员' ||  rightsContains(u);

    }

    public Boolean rightsContains(User u ){
        List<String> rights = Label.PerformanceImportRight.split(',',-1);
        for(String right : rights){
            if(right == u.Name || right == u.Profile.Name )return true;
        }
        return false;
    }
    private String getYear(){

    	if(System.today().Month() <=3 ) return (System.today().year()-1)+'年';
    	return (System.today().year())+'年';
    }
    private String getQuater(){
    	if(System.today().Month() <=3 ) return '4';
    	if(System.today().Month() <= 6) return '1';
    	if(System.today().Month() <= 9) return '2';
    	if(System.today().Month() <= 12) return '3';
    	return '1';
    }
  
    public void init(){
    	Map<String,Object> dataMap =new Map<String,Object>();
    	dataMap.put('fields', getAllFields());
		dataMap.put('year', getYear());
		dataMap.put('quater', getQuater());
		dataMap.put('company', ImportObject.getPicklistValues('SalesPerformanceDataSheet__c', 'Company__c', true));


    	dataJson = EncodingUtil.urlEncode(JSON.serialize(dataMap), 'UTF-8');
    }

    public Map<String ,String> getAllFields(){

    	Map<String,String>fM = new Map<String,String>();
		Schema.DescribeSobjectResult m = SalesPerformanceDataSheet__c.sObjectType.getDescribe();
	        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

        for (String field : fieldMap.keySet()) {
             
             Schema.SObjectField sf  = fieldMap.get(field);
             fM.put(sf.getDescribe().getLocalName(),sf.getDescribe().getLabel());
             //System.debug(sf.getDescribe().getLocalName()+' > ' +sf.getDescribe().getLabel());
          
        }

        return fM;
    }


    public void searchDetail(){
    		msg = '';
    		try {
    		    Map<String,Object>searchMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson, 'UTF-8'));

    	
		    	Schema.DescribeSobjectResult m = SalesPerformanceDataSheet__c.sObjectType.getDescribe();
		        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

		        String sql = 'select ';
		        List<String> fields = new List<String>();
		        for (String field : fieldMap.keySet()) {
		             fields.add(field);
		        }
		        sql += String.join(fields, ',');

		    	sql += ', RecordType.DeveloperName ,TerminalAccount__r.Name,Account__r.Name  from SalesPerformanceDataSheet__c where     ';

		    	String rtype = DataUtil.getStringValue(searchMap.get('rtype'));
		    	String ortype = DataUtil.getStringValue(searchMap.get('ortype'));
                String company = DataUtil.getStringValue(searchMap.get('company'));
                String quater = DataUtil.getStringValue(searchMap.get('quater'));
                String year = DataUtil.getStringValue(searchMap.get('year'));
                String workno = DataUtil.getStringValue(searchMap.get('workno'));

                if(searchMap.containsKey('sum')){

                    if(rtype == 'ReagentPerformanceSum')sumBaseRegent(company,rtype,year,quater);
                    if(rtype == 'InstrumentPerformanceSum')sumBaseEquip(company,rtype,year,quater);
                    if(rtype =='ReagentIncrementalPerformanceSum')sumBaseRegentIncrease(company,rtype,year,quater);
                    if(rtype =='AgentIncrementPerformanceSum' || rtype =='AnnualIncrementPerformanceSum')sumRegent(company,rtype,year);
                    return;
                }

		    	if(!String.isBlank(rtype))sql += '    RecordType.DeveloperName  in (\''+rtype +'\',\''+ortype +'\' )  ';
		    	if(String.isBlank(rtype))throw new DmlException('请选择需要查询的基础数据类型') ;


		    	//if(String.isBlank(workno))throw new DmlException('请选择需调整绩效用户') ;

		    	//List<User> workers = [select Id,ExuserCode__c,Nam,EmployeeNumber    from User where  ExuserCode__c =:workno or Name =:workno ];
		    	//if(workers.isEmpty())throw new DmlException('请选择需调整绩效用户') ;

		    	//if(!workers.isEmpty() && workers[0].EmployeeNumber != null )sql += ' and EmployeeNumber__c =\''+workers[0].EmployeeNumber +'\' ';
                if(!String.isBlank(workno))sql += ' and (EmployeeNumber__c =\'' +workno+'\' or Name__c = \''+workno+'\') ';
		    	//if(!workers.isEmpty() && workers[0].ExuserCode__c == null )sql += ' and Name__c like \'%'+workers[0].Name +'%\' ';
		    	
		    	if(!String.isBlank(quater))sql += ' and Quarter__c =\''+quater +'\' ';
		    	if(String.isBlank(quater))throw new DmlException('请选择季度!') ;

		    	String province = DataUtil.getStringValue(searchMap.get('province'));
		    	if(!String.isBlank(province))sql += ' and Province__c like\'%'+province +'%\' ';

		    	if(!String.isBlank(year))sql += ' and Year__c =\''+year +'\' ';
		    	if(String.isBlank(year))throw new DmlException('请选择年度!') ;

		    	String accName = DataUtil.getStringValue(searchMap.get('accName'));
		    	if(!String.isBlank(accName))sql += ' and (Account__r.Name like \'%'+accName +'%\' or AccountPK__c like \'%'+accName +'%\') ';

		    	String terminalName = DataUtil.getStringValue(searchMap.get('terminalName'));
		    	if(!String.isBlank(terminalName))sql += ' and (TerminalAccount__r.Name like \'%'+terminalName +'%\' or TerminalAccountPK__c like \'%'+terminalName +'%\') ';

		    	if(!String.isBlank(company))sql += ' and Company__c =\''+company +'\' ';

		    	String limitNum   = DataUtil.getStringValue(searchMap.get('limit'));
		    	sql += ' limit ' +(String.isBlank(limitNum) ? '500' : limitNum )+ ' ' ; 
		    	System.debug('SalesPerformanceDataSheetController==>'+sql);
		    	List<Map<String,Object>> tmp = new List<Map<String,Object>>();
		    	for (SalesPerformanceDataSheet__c sp : Database.query(sql) ) {
		    		Map<String,Object>t = new Map<String,Object>();
		    		

		    		for (String key  : SalesPerformanceDataImportController.fbeanMap.keySet()) {
		    			t.put(key,sp.get(key) );
		    		}
		    		t.put('Account__r',sp.getSObject('Account__r'));
		    		t.put('TerminalAccount__r',sp.getSObject('TerminalAccount__r'));
		    		t.put('RecordType',sp.getSObject('RecordType'));
		    		tmp.add(t);

		    	}
		    	dataJson = EncodingUtil.urlEncode( JSON.serialize(tmp ), 'UTF-8');
    		}
    		catch (Exception  e) {
    		    msg = e.getMessage();
    		}
    		
    		
    }

    public void deleteSum(){

        msg = '';
        SavePoint sp = Database.setSavepoint();
        try {
            
            if(String.isBlank(deleType) || String.isBlank(deleCompany))msg = '操作失败:参数异常!';
            if(String.isNotBlank(msg)) return;
            delete [select Id from SalesPerformanceDataSheet__c where RecordType.DeveloperName =:deleType and Company__c =:deleCompany  and Quarter__c =:getQuater() and Year__c =:getYear() and RecordType.DeveloperName like '%Sum' ];

            msg = '操作成功!';
        }
        catch (Exception e) {
           
           Database.rollback(sp);
           msg = '操作失败:'+e.getMessage(); 
        }
        deleType ='';
        deleCompany = '';

        
    }

    public void sumBaseEquip(String company, String rtype,String year ,String quater ){

        List<Object> tmp = new List<Object>();

        for(AggregateResult arg : [select Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c,InstrumentClasses__c , 

            sum(BudgetQuantity__c) BudgetQuantity__c,sum(BudgetQuantityQ1__c) BudgetQuantityQ1__c, sum(BudgetQuantityQ2__c) BudgetQuantityQ2__c,sum(BudgetQuantityQ3__c) BudgetQuantityQ3__c, sum(BudgetQuantityQ4__c) BudgetQuantityQ4__c ,
            sum(ActualQuantity__c) ActualQuantity__c , sum(ActualQuantityQ1__c) ActualQuantityQ1__c ,sum(ActualQuantityQ2__c) ActualQuantityQ2__c ,sum(ActualQuantityQ3__c) ActualQuantityQ3__c,sum(ActualQuantityQ4__c) ActualQuantityQ4__c 

             from SalesPerformanceDataSheet__c where Year__c =:year and Quarter__c in:getQuaters(quater) and Company__c =:company

              and RecordType.DeveloperName =:rtype and NotActive__c = false 
              
             group by    Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c,InstrumentClasses__c
                
             ] ){
            
            /*Map<String,Object> dataMap = new Map<String,Object>();

            dataMap.put('InstrumentClasses__c',arg.get('InstrumentClasses__c'));
            dataMap.put('Company__c',arg.get('Company__c'));
            dataMap.put('EmployeeNumber__c',arg.get('EmployeeNumber__c'));
            dataMap.put('Name__c',arg.get('Name__c'));
            dataMap.put('JobCategory__c',arg.get('JobCategory__c'));
            dataMap.put('SalesMarket__c',arg.get('SalesMarket__c'));

            dataMap.put('BudgetQuantity__c',arg.get('BudgetQuantity__c'));

            dataMap.put('BudgetQuantityQ1__c',arg.get('BudgetQuantityQ1__c'));
            dataMap.put('BudgetQuantityQ2__c',arg.get('BudgetQuantityQ2__c'));
            dataMap.put('BudgetQuantityQ3__c',arg.get('BudgetQuantityQ3__c'));
            dataMap.put('BudgetQuantityQ4__c',arg.get('BudgetQuantityQ4__c'));
            
            dataMap.put('ActualQuantity__c',arg.get('ActualQuantity__c'));

            dataMap.put('ActualQuantityQ1__c',arg.get('ActualQuantityQ1__c'));
            dataMap.put('ActualQuantityQ2__c',arg.get('ActualQuantityQ2__c'));
            dataMap.put('ActualQuantityQ3__c',arg.get('ActualQuantityQ3__c'));
            dataMap.put('ActualQuantityQ4__c',arg.get('ActualQuantityQ4__c'));


            tmp.add(dataMap);
            */
            tmp.add(generateData(arg));

        }
        dataJson = EncodingUtil.urlEncode( JSON.serialize(tmp ), 'UTF-8');

    }
    public void sumBaseRegent(String company, String rtype,String year ,String quater  ){

        List<Object> tmp = new List<Object>();
        for(AggregateResult arg : [select  Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c,ReagentCategory__c ,
            sum(ActualSales__c) ActualSales__c, sum(ActualSalesQ1__c) ActualSalesQ1__c, sum(ActualSalesQ2__c) ActualSalesQ2__c,sum(ActualSalesQ3__c) ActualSalesQ3__c, sum(ActualSalesQ4__c) ActualSalesQ4__c ,
            sum(BudgetSales__c) BudgetSales__c , sum(BudgetSalesQ1__c) BudgetSalesQ1__c ,sum(BudgetSalesQ2__c) BudgetSalesQ2__c ,sum(BudgetSalesQ3__c) BudgetSalesQ3__c,sum(BudgetSalesQ4__c) BudgetSalesQ4__c ,
            sum(LastYearSalesVolume__c) LastYearSalesVolume__c , sum(LastYearSalesVolumeQ1__c) LastYearSalesVolumeQ1__c ,sum(LastYearSalesVolumeQ2__c) LastYearSalesVolumeQ2__c ,sum(LastYearSalesVolumeQ3__c) LastYearSalesVolumeQ3__c,sum(LastYearSalesVolumeQ4__c) LastYearSalesVolumeQ4__c 

             from SalesPerformanceDataSheet__c where Year__c =:year and Quarter__c in:getQuaters(quater) and Company__c =:company

              and RecordType.DeveloperName =:rtype and NotActive__c = false 
              
             group by   Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c, ReagentCategory__c
                
             ] ){
            /*
            Map<String,Object> dataMap = new Map<String,Object>();
            dataMap.put('ReagentCategory__c',arg.get('ReagentCategory__c'));
            dataMap.put('Company__c',arg.get('Company__c'));
            dataMap.put('EmployeeNumber__c',arg.get('EmployeeNumber__c'));
            dataMap.put('Name__c',arg.get('Name__c'));
            dataMap.put('JobCategory__c',arg.get('JobCategory__c'));
            dataMap.put('SalesMarket__c',arg.get('SalesMarket__c'));

            dataMap.put('ActualSales__c',arg.get('ActualSales__c'));

            dataMap.put('ActualSalesQ1__c',arg.get('ActualSalesQ1__c'));
            dataMap.put('ActualSalesQ2__c',arg.get('ActualSalesQ2__c'));
            dataMap.put('ActualSalesQ3__c',arg.get('ActualSalesQ3__c'));
            dataMap.put('ActualSalesQ4__c',arg.get('ActualSalesQ4__c'));
           
            dataMap.put('BudgetSales__c',arg.get('BudgetSales__c'));

            dataMap.put('BudgetSalesQ1__c',arg.get('BudgetSalesQ1__c'));
            dataMap.put('BudgetSalesQ2__c',arg.get('BudgetSalesQ2__c'));
            dataMap.put('BudgetSalesQ3__c',arg.get('BudgetSalesQ3__c'));
            dataMap.put('BudgetSalesQ4__c',arg.get('BudgetSalesQ4__c'));

            dataMap.put('LastYearSalesVolume__c',arg.get('LastYearSalesVolume__c'));

            dataMap.put('LastYearSalesVolumeQ1__c',arg.get('LastYearSalesVolumeQ1__c'));
            dataMap.put('LastYearSalesVolumeQ2__c',arg.get('LastYearSalesVolumeQ2__c'));
            dataMap.put('LastYearSalesVolumeQ3__c',arg.get('LastYearSalesVolumeQ3__c'));
            dataMap.put('LastYearSalesVolumeQ4__c',arg.get('LastYearSalesVolumeQ4__c'));



            tmp.add(dataMap);
            */
            tmp.add(generateData(arg));

        }
        dataJson = EncodingUtil.urlEncode( JSON.serialize(tmp ), 'UTF-8');
    }

    public List<String> getQuaters(String quater){
        Integer tp =  Integer.valueOf(quater) ;
        Integer i = 1;
        List<String> qs = new List<String>();
        while(i <= tp ){
            qs.add(String.valueOf(i));
            i ++;
        }
        return qs;
    }
    public void sumBaseRegentIncrease(String company, String rtype,String year ,String quater  ){

        
        List<Object> tmp = new List<Object>();
        for(AggregateResult arg : [select   Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c,IncrementalCcategory__c,Category__c,
            sum(ActualSales__c) ActualSales__c, sum(ActualSalesQ1__c) ActualSalesQ1__c, sum(ActualSalesQ2__c) ActualSalesQ2__c,sum(ActualSalesQ3__c) ActualSalesQ3__c, sum(ActualSalesQ4__c) ActualSalesQ4__c ,
            sum(LastYearSalesVolume__c) LastYearSalesVolume__c , sum(LastYearSalesVolumeQ1__c) LastYearSalesVolumeQ1__c ,sum(LastYearSalesVolumeQ2__c) LastYearSalesVolumeQ2__c ,sum(LastYearSalesVolumeQ3__c) LastYearSalesVolumeQ3__c,sum(LastYearSalesVolumeQ4__c) LastYearSalesVolumeQ4__c 
             from SalesPerformanceDataSheet__c where Year__c =:year and Quarter__c in:getQuaters(quater) and Company__c =:company

              and RecordType.DeveloperName =:rtype  and NotActive__c = false 
              
             group by  Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c,IncrementalCcategory__c,Category__c
                
             ] ){
            /*
            Map<String,Object> dataMap = new Map<String,Object>();
            dataMap.put('IncrementalCcategory__c',arg.get('IncrementalCcategory__c'));
            dataMap.put('Company__c',arg.get('Company__c'));
            dataMap.put('EmployeeNumber__c',arg.get('EmployeeNumber__c'));
            dataMap.put('Name__c',arg.get('Name__c'));
            dataMap.put('JobCategory__c',arg.get('JobCategory__c'));
            dataMap.put('SalesMarket__c',arg.get('SalesMarket__c'));
            dataMap.put('Category__c',arg.get('Category__c'));

            dataMap.put('ActualSales__c',arg.get('ActualSales__c'));

            dataMap.put('ActualSalesQ1__c',arg.get('ActualSalesQ1__c'));
            dataMap.put('ActualSalesQ2__c',arg.get('ActualSalesQ2__c'));
            dataMap.put('ActualSalesQ3__c',arg.get('ActualSalesQ3__c'));
            dataMap.put('ActualSalesQ4__c',arg.get('ActualSalesQ4__c'));
           
           

            dataMap.put('LastYearSalesVolume__c',arg.get('LastYearSalesVolume__c'));

            dataMap.put('LastYearSalesVolumeQ1__c',arg.get('LastYearSalesVolumeQ1__c'));
            dataMap.put('LastYearSalesVolumeQ2__c',arg.get('LastYearSalesVolumeQ2__c'));
            dataMap.put('LastYearSalesVolumeQ3__c',arg.get('LastYearSalesVolumeQ3__c'));
            dataMap.put('LastYearSalesVolumeQ4__c',arg.get('LastYearSalesVolumeQ4__c'));



            tmp.add(dataMap);
            */
             tmp.add(generateData(arg));
        }
        dataJson = EncodingUtil.urlEncode( JSON.serialize(tmp ), 'UTF-8');
    }


    public void sumRegent(String company, String rtype , String year ){

        List<Object> tmp = new List<Object>();
        for(AggregateResult arg : [select   Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c,
            
            sum(ActualSales__c) ActualSales__c, 
            sum(LastYearSalesVolume__c) LastYearSalesVolume__c , 
            sum(BudgetSales__c) BudgetSales__c  
            
            from SalesPerformanceDataSheet__c where Year__c =:year  and Company__c =:company

              and RecordType.DeveloperName =:rtype and NotActive__c = false 
              
             group by  Company__c , EmployeeNumber__c,Name__c,JobCategory__c,SalesMarket__c
             ] ){
            
            /*
            dataMap.put('Company__c',arg.get('Company__c'));
            dataMap.put('EmployeeNumber__c',arg.get('EmployeeNumber__c'));
            dataMap.put('Name__c',arg.get('Name__c'));
            dataMap.put('JobCategory__c',arg.get('JobCategory__c'));
            dataMap.put('SalesMarket__c',arg.get('SalesMarket__c'));

            dataMap.put('LastYearSalesVolume__c',arg.get('LastYearSalesVolume__c'));
            dataMap.put('ActualSales__c',arg.get('ActualSales__c'));
            dataMap.put('BudgetSales__c',arg.get('BudgetSales__c'));
            */
        
            tmp.add(generateData(arg));
        }
        dataJson = EncodingUtil.urlEncode( JSON.serialize(tmp ), 'UTF-8');
    }


    public void setValue(Map<String,Object> dataMap, AggregateResult arg  ,String fieldName ){
        try{
           if(arg.get(fieldName) != null )dataMap.put(fieldName,arg.get(fieldName));
        }catch(Exception e ){}
    }

    public  Map<String,Object>  generateData(AggregateResult arg ){

            Map<String,Object> sum = new Map<String,Object>();
            setValue(sum,arg,'InstrumentClasses__c');
            setValue(sum,arg,'Company__c');
            setValue(sum,arg,'EmployeeNumber__c');
            setValue(sum,arg,'Name__c');
            setValue(sum,arg,'JobCategory__c');
            setValue(sum,arg,'SalesMarket__c');

            setValue(sum,arg,'BudgetQuantity__c');
            setValue(sum,arg,'BudgetQuantityQ1__c');
            setValue(sum,arg,'BudgetQuantityQ2__c');
            setValue(sum,arg,'BudgetQuantityQ3__c');
            setValue(sum,arg,'BudgetQuantityQ4__c');

            setValue(sum,arg,'ActualQuantity__c');
            setValue(sum,arg,'ActualQuantityQ1__c');
            setValue(sum,arg,'ActualQuantityQ2__c');
            setValue(sum,arg,'ActualQuantityQ3__c');
            setValue(sum,arg,'ActualQuantityQ4__c');

            setValue(sum,arg,'LastYearSalesVolume__c');
            setValue(sum,arg,'LastYearSalesVolumeQ1__c');
            setValue(sum,arg,'LastYearSalesVolumeQ2__c');
            setValue(sum,arg,'LastYearSalesVolumeQ3__c');
            setValue(sum,arg,'LastYearSalesVolumeQ4__c');

            setValue(sum,arg,'IncrementalCcategory__c');
            setValue(sum,arg,'Category__c');
            setValue(sum,arg,'ReagentCategory__c');

            setValue(sum,arg,'ActualSales__c');
            setValue(sum,arg,'ActualSalesQ1__c');
            setValue(sum,arg,'ActualSalesQ2__c');
            setValue(sum,arg,'ActualSalesQ3__c');
            setValue(sum,arg,'ActualSalesQ4__c');

            setValue(sum,arg,'BudgetSales__c');
            setValue(sum,arg,'BudgetSalesQ1__c');
            setValue(sum,arg,'BudgetSalesQ2__c');
            setValue(sum,arg,'BudgetSalesQ3__c');
            setValue(sum,arg,'BudgetSalesQ4__c');

            return sum ;



    }


    public  void  setNil(){

    	dataJson = '[]';
    	searchJson = '{}';
    }


    public static Boolean strQarter(String s ){
        Pattern paramPattern  = Pattern.compile('Q[1-4]__c');
        Matcher m1 = paramPattern.matcher(s);
        return m1.find();

    }

    public static String trans(String wno){
        if(wno == null)return null;
        if(wno.length() >=6 ) return wno ;
        while(wno.length() <6 ){
            wno = '0'+wno;
        }
        return wno;

    }
    //按公司汇总数据
    public void sumData(){
        msg = '';
        try {

            if(String.isBlank(deleCompany))throw new DmlException('请选择要汇总的公司!');

            Database.executeBatch(new SalePerformanceDataCalcBatch(getYear(),getQuater(),deleCompany,isIncrease),1);
            deleCompany = '';
            msg = '操作成功,请稍等再刷新数据!';
        }catch (Exception e) {
            msg = '操作失败:'+e.getMessage();
        }

        

    }
    @RemoteAction 
    public static String importData(String datas , String type, String quater ){

    	Map<String,Object> resultMap = new Map<String,Object>();
    	List<Object>errList = new List<Object>();
    	

		List<Object> saveList = (List<Object> )JSON.deserializeUntyped(EncodingUtil.urlDecode(datas, 'UTF-8'));

    	String rtTypeId = Utils.getRecordTypeIdByDevNameAndObjName(type, 'SalesPerformanceDataSheet__c');

	    //
	    Map<String,SalesPerformanceDataSheet__c> spM = new Map<String,SalesPerformanceDataSheet__c>();
	    Set<String> keys = new Set<String>();
	    Map<String,Map<String,Object>> moM = new Map<String,Map<String,Object>>();
    	List<SalesPerformanceDataSheet__c>spList = new List<SalesPerformanceDataSheet__c>();
    	Set<String > spset = new Set<String>();


        String quaterStr  = 'Q'+quater;

        String wono = '';
        String year = '';
        String company = '';
    	for(Object o : saveList){

    		Map<String,Object> mo = (Map<String,Object>)o;
    		try {
	    		SalesPerformanceDataSheet__c sp = new SalesPerformanceDataSheet__c();
	        	sp.RecordTypeId = rtTypeId;
                Set<String> fieldContinues = new Set<String>{'Id','Account__c','TerminalAccount__c','NotActive__c'};
	        	for (String fieldName :mo.keySet() ) {
	        		if(fieldContinues.contains(fieldName))continue;

                    //排除 调整其他季度的数据 
                    if( strQarter(fieldName)  && !fieldName.contains(quaterStr))continue; 
	        		sp.put(fieldName, DataUtil.dataHandler(mo.get(fieldName),fbeanMap.get(fieldName) ) );
	        	}
                sp.EmployeeNumber__c  =trans(sp.EmployeeNumber__c);
                //if( sp.EmployeeNumber__c  == null || sp.EmployeeNumber__c.length() < 6 ) throw new DmlException('工号不能为空且长度必须6位!');
	        	
                sp.SalesPerformanceDataSheet__c = (String)mo.get('Id');
	        	if(String.isNotBlank(sp.SalesPerformanceDataSheet__c) )spset.add(sp.SalesPerformanceDataSheet__c);
	        	//String key = SalesPerformanceDataSheetHandler.getKeyWithOutAdjustNo(sp);

	    		sp.NotActive__c = false;
                wono = sp.EmployeeNumber__c;
                year = sp.Year__c;
                company = sp.Company__c;
                if(String.isBlank(sp.Year__c))throw new DmlException('年份不能为空!');
                if(String.isBlank(sp.EmployeeNumber__c))throw new DmlException('工号不能为空!');
                if(String.isBlank(sp.Company__c))throw new DmlException('归口公司不能为空!');
                sp.IsImport__c = true;
	    		spList.add(sp);
	    		// keys.add(key+'%');
	    		// if(spM.containsKey(key))new DmlException('存在重复数据:');
	      //   	spM.put(key,sp);
	        	//moM.put(key, mo);

        	}catch (Exception e) {
	           	mo.put('msg', '保存失败!'+e.getMessage() + '  '+ e.getStackTraceString());
	            errList.add(mo);
	    	}

    	} 
    	//saveList.clear();

    	List<SalesPerformanceDataSheet__c> updateList = new List<SalesPerformanceDataSheet__c>();
    	
    	//将之前的调整数据变为失效 
    	for (SalesPerformanceDataSheet__c sp: [select Id from SalesPerformanceDataSheet__c 
            where  Id in:spset  ] ) {
    		
    		sp.NotActive__c = true;
    		updateList.add(sp);
    	}

    	/*if(!spM.isEmpty()){
    		for (String key  : spM.keySet() ) {

    			Map<String,Object> mo  = moM.get(key);
    			mo.put('msg','没有匹配到基础数据,匹配键:'+key);
	            errList.add(mo);
	            moM.remove(key);
    		}
    	}
    	*/

    	SavePoint sp = Database.setSavepoint();
    	try {

            //如果 是导入汇总数据 
            if(type.contains('Sum')){

                if(type == 'AnnualIncrementPerformanceSum' || type == 'AgentIncrementPerformanceSum')quater = null;
                
                delete [select Id from SalesPerformanceDataSheet__c where RecordType.DeveloperName =:type 
                   and Year__c =:year and Quarter__c=:quater and EmployeeNumber__c =:wono  and Company__c=:company 
                 ];



            }
    	   if(!spList.isEmpty()) insert spList;
    	   if(!updateList.isEmpty())update updateList;
    	}catch (Exception e) {
    	    Database.rollback(sp);
    	    for(Object m : saveList){
    	    	Map<String,Object> mo = (Map<String,Object>)m;
                mo.put('msg', '保存失败!'+e.getMessage() + '  '+ e.getStackTraceString());
                errList.add(mo);
            }
    	}
    	resultMap.put('errData', errList);

    	return EncodingUtil.urlEncode(JSON.serialize(resultMap), 'UTF-8') ;

    	
    }
}